<script setup>
import { useAppStore, useWMTSStore } from '@/stores'
import ExceptionLogger from '@/utils/errorHandler'
import { useBoolean } from '@/hooks/useBoolean'

const appStore = useAppStore()
const wmtsStore = useWMTSStore()
const selectedValue = ref('选择要加载的WMTS图层')
const fileInput = ref(null)
const fileName = ref('') // 用于存储文件名
const fileError = ref(false) // 用于控制文件名颜色
const layerOptions = ref([])
const loading = ref(false)
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)
const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(387) : ref(427)) : appStore.showFooter ? ref(427) : ref(472)
const { bool: addLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const computedHeight = computed(() => windowHeight.value - adaptHeight.value + 210)
const wmtsInfo = reactive({
  DPI: {
    title: 'DPI:',
    value: ''
  },
  Title: {
    title: '地图:',
    value: ''
  },
  TileMatrixSetName: {
    title: '矩阵集:',
    value: ''
  },
  TopLeftCorner: {
    title: '左上角起算点:',
    value: ''
  },
  BoundingBox: {
    title: '范围:',
    value: ''
  },
  MatrixIds: {
    title: '矩阵ID(MatrixIds):',
    value: ''
  },
  ScaleDenominator: {
    title: '比例尺分母:',
    value: ''
  },
  Resolution: {
    title: '分辨率(Resolution):',
    value: ''
  }
})
const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

async function handleUpdateValue(_, option) {
  startLoading()
  try {
    wmtsStore.setCurrentTileMatrixSet(option.label)
    await wmtsStore.setLeafletAddCode()
    await wmtsStore.setOpenlayersAddCode()
    await wmtsStore.setCesiumAddCode()
    await wmtsStore.setSuperMap3DAddCode()
  } catch (error) {
    fileError.value = true
    ExceptionLogger.wmtsHandleException(error)
  } finally {
    endLoading()
  }
}

// 打开文件选择器
function selectFile() {
  fileInput.value.click()
}

// 处理文件选择
async function handleFileChange(event) {
  const file = event.target.files[0]
  if (file) {
    fileError.value = false
    fileName.value = file.name
    const reader = new FileReader()
    reader.onload = async (e) => {
      const fileContent = e.target.result
      startLoading()
      try {
        await wmtsStore.initWMTSInfoByFile(fileContent)
        await wmtsStore.setLeafletAddCode()
        await wmtsStore.setOpenlayersAddCode()
        await wmtsStore.setCesiumAddCode()
        await wmtsStore.setSuperMap3DAddCode()
      } catch (error) {
        fileError.value = true
        ExceptionLogger.wmtsHandleException(error)
      } finally {
        loading.value = false
        endLoading()
      }
    }
    reader.readAsText(file)
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(
  () => wmtsStore.currentTileMatrixSet,
  () => {
    if (!wmtsStore.currentTileMatrixSet) return
    wmtsInfo.DPI.value = wmtsStore.currentTileMatrixSet.DPI
    wmtsInfo.Title.value = wmtsStore.currentLayerTitle
    wmtsInfo.TileMatrixSetName.value = wmtsStore.currentTileMatrixSet.TileMatrixSetName
    wmtsInfo.TopLeftCorner.value = wmtsStore.currentTileMatrixSet.TileMatrix?.TopLeftCorner[0]
    wmtsInfo.BoundingBox.value = JSON.stringify(wmtsStore.getTileMatrixSetBBox(wmtsStore.currentTileMatrixSet.SupportedCRS))
    wmtsInfo.MatrixIds.value = wmtsStore.currentTileMatrixSet.TileMatrix?.Identifier
    wmtsInfo.ScaleDenominator.value = wmtsStore.currentTileMatrixSet.TileMatrix?.ScaleDenominator
    wmtsInfo.Resolution.value = wmtsStore.currentTileMatrixSet.TileMatrix?.Resolution
  }
)

watch(
  () => wmtsStore.wmtsInfo.mapLayer,
  () => {
    if (!wmtsStore.wmtsInfo.mapLayer) return
    if (Array.isArray(wmtsStore.wmtsInfo.mapLayer) && wmtsStore.wmtsInfo.mapLayer.length > 0) {
      layerOptions.value = wmtsStore.wmtsInfo.mapLayer.map((item) => {
        return {
          label: item.Title,
          key: item.Identifier,
          children: item.TileMatrixSet.map((matrix) => ({
            label: matrix.TileMatrixSetName,
            key: matrix.TileMatrixSetName
          }))
        }
      })
      selectedValue.value = layerOptions.value[0].children[0]?.label
    }
  }
)

watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)

watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card>
    <n-grid :x-gap="0" :y-gap="8" :cols="2">
      <n-gi>
        <n-flex>
          <n-input-group>
            <div style="display: flex; align-items: center; min-width: 400px">
              <n-button type="primary" :loading="loading" @click="selectFile">
                <template #icon>
                  <icon-park-outline-data />
                </template>
                选择文件
              </n-button>
              <span :style="{ color: fileError ? 'red' : '#18a058' }" style="margin-left: 10px" v-if="fileName">{{ fileName }}</span>
              <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" accept=".xml" />
            </div>
          </n-input-group>
        </n-flex>
      </n-gi>
      <n-gi>
        <n-flex class="w-80 ml-auto">
          <n-tree-select :options="layerOptions" placeholder="请选择要加载的地图矩阵集合" v-model:value="selectedValue" @update:value="handleUpdateValue" check-strategy="child" />
        </n-flex>
      </n-gi>
    </n-grid>
  </n-card>
  <n-card embedded :style="{ height: `${computedHeight}px` }" class="flex-1 mt-2">
    <n-infinite-scroll :style="{ height: `${computedHeight - 50}px` }">
      <n-list hoverable>
        <template v-for="(item, index) in wmtsInfo" :key="index">
          <n-list-item>
            <n-thing :title="item.title" content-style="" :style="{ color: appStore.primaryColor }">
              <template #description>
                {{ item.value }}
                <copy-text v-model:value="item.value"></copy-text>
              </template>
            </n-thing>
          </n-list-item>
        </template>
      </n-list>
    </n-infinite-scroll>
    <Loading v-if="addLoading" />
  </n-card>
</template>
